package com.cch.platform.fiter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;

import com.cch.platform.base.bean.BaseUser;
import com.cch.platform.util.MapUtil;
import com.cch.platform.web.WebUtil;

public class LoginFilter implements Filter{

	protected final Log logger = LogFactory.getLog(getClass());// 日志
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest hrequest=(HttpServletRequest) request;
		String path=hrequest.getServletPath();
		logger.info("Begin:"+path);
		//排除登录页面
		if("/base/login/login.jsp".equals(path) || "/base/userlogin/login.do".equals(path)){
			chain.doFilter(request, response);
			logger.info("End:"+path);
			return;
		}
		//排除测试页面
		if(path!=null&&path.indexOf("/base/test/")>-1){
			chain.doFilter(request, response);
			logger.info("End:"+path);
			return;
		}
		//检验是否登录
		BaseUser user=(BaseUser)hrequest.getSession().getAttribute("user");
		if(user!=null && user instanceof BaseUser){
			WebUtil.setUser(user);
			chain.doFilter(request, response);
		}else{
			HttpServletResponse hresponse=(HttpServletResponse) response;
			if(path.endsWith(".do")){
				hresponse.getWriter().append("{sucesse:'false',location:'"+hrequest.getContextPath()+"/base/login/login.jsp'}");	
			}else{
				hresponse.sendRedirect(hrequest.getContextPath()+"/base/login/login.jsp");
			}
		}
		logger.info("End:"+path);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
